/*

 */

package forum.command.console;

import forum.command.*;

import java.util.HashMap;
import java.util.Iterator;

public class Console {
    private static HashMap<String,Command> commands = new HashMap<String, Command>();
    private CommandContext context;

    static {
        commands.put("login", new LogInCommand());
        commands.put("register", new RegistrationCommand());
        commands.put("new_cat", new CreateCategoryCommand());
        commands.put("new_topic", new CreateTopicCommand());
        commands.put("open_cat",new OpenCategoryCommand());
        commands.put("open_topic", new OpenTopicCommand());
        commands.put("del_topic", new DeleteTopicCommand());
        commands.put("post", new PostMessageCommand());
        commands.put("logout", new LogOutCommand());
        commands.put("exit", new ExitCommand());
        commands.put("help", new ManualCommand());
    }

    public Console() {
        context = new CommandContext(null,null,null);
    }

    public void run(String cmd) {
        Command command = parse(cmd);
        command.execute();
        command.updateContext(context);
    }

    private Command parse(String cmd) {
       // final int MAX_COMMANDS = 4;
        if(cmd == null || cmd.length() == 0) {
            throw new IllegalArgumentException("");
        }
        String parsedText[] = cmd.split(" *\\| *");
        Command parsedCommand = commands.get(parsedText[0]);
        if(parsedCommand == null) {
            throw new NullPointerException("No such command '"+parsedText[0]+"'");
        }
        String args[];
        if (parsedText.length == 1) {
            args = new String[1];
        } else
            args = new String[parsedText.length-1];
        System.arraycopy(parsedText,1,args,0,parsedText.length-1);
        parsedCommand.setContext(context);
        parsedCommand.setParameters(args);
        return parsedCommand;
    }

    public static class ManualCommand implements Command {

        Command cmd;
        @Override
        public void execute() {
            if (cmd != null)
                System.out.println(cmd.help());
            else {
                Iterator iterator = commands.keySet().iterator();
                System.out.println("List of  available commands");
                while (iterator.hasNext()) {
                    System.out.println(iterator.next());
                }
                System.out.println(help());
            }
        }

        @Override
        public void setContext(CommandContext context) {

        }

        @Override
        public void updateContext(CommandContext context) {

        }

        @Override
        public String help() {
            return "Type 'help %commandname% to get help for this command'";
        }

        public void setParameters(String... args) {
            cmd = commands.get(args[0]);
        }
    }
}
